package cn.iocoder.an.module.business.service.storeinit;

import cn.hutool.core.collection.CollUtil;
import cn.iocoder.an.framework.security.core.LoginUser;
import cn.iocoder.an.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.an.module.business.controller.admin.drawconfig.vo.DrawConfigImportVo;
import cn.iocoder.an.module.business.controller.admin.drawconfig.vo.DrawConfigSaveReqVO;
import cn.iocoder.an.module.business.controller.admin.equipmentmanage.vo.ImportRespVO;
import cn.iocoder.an.module.business.controller.admin.storemanage.vo.StoreManagePageReqVO;
import cn.iocoder.an.module.business.dal.dataobject.drawconfig.DrawConfigDO;
import cn.iocoder.an.module.business.dal.dataobject.storemanage.StoreManageDO;
import cn.iocoder.an.module.business.dal.mysql.drawconfig.DrawConfigMapper;
import cn.iocoder.an.module.business.dal.mysql.storemanage.StoreManageMapper;
import cn.iocoder.an.module.system.dal.dataobject.user.AdminUserDO;
import cn.iocoder.an.module.system.service.permission.PermissionService;
import cn.iocoder.an.module.system.service.user.AdminUserService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.micrometer.common.util.StringUtils;
import org.springframework.stereotype.Service;
import jakarta.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;

import cn.iocoder.an.module.business.controller.admin.storeinit.vo.*;
import cn.iocoder.an.module.business.dal.dataobject.storeinit.StoreInitDO;
import cn.iocoder.an.framework.common.pojo.PageResult;
import cn.iocoder.an.framework.common.pojo.PageParam;
import cn.iocoder.an.framework.common.util.object.BeanUtils;

import cn.iocoder.an.module.business.dal.mysql.storeinit.StoreInitMapper;

import static cn.iocoder.an.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.an.framework.common.util.collection.CollectionUtils.convertList;
import static cn.iocoder.an.framework.common.util.collection.CollectionUtils.diffList;
import static cn.iocoder.an.module.business.enums.ErrorCodeConstants.*;

/**
 * 期初库存台账 Service 实现类
 *
 * @author zzy
 */
@Service
@Validated
public class StoreInitServiceImpl implements StoreInitService {

    @Resource
    private StoreInitMapper storeInitMapper;

    @Resource
    private AdminUserService adminUserService;

    @Resource
    private PermissionService permissionService;

    @Resource
    private DrawConfigMapper drawConfigMapper;

    @Resource
    private StoreManageMapper storeManageMapper;


    @Override
    public Long createStoreInit(StoreInitSaveReqVO createReqVO) {
        // 插入
        StoreInitDO storeInit = BeanUtils.toBean(createReqVO, StoreInitDO.class);
        checkDrawConfig(createReqVO, "add");
        storeInitMapper.insert(storeInit);

        // 返回
        return storeInit.getId();
    }

    @Override
    public void updateStoreInit(StoreInitSaveReqVO updateReqVO) {
        // 校验存在
        validateStoreInitExists(updateReqVO.getId());
        checkDrawConfig(updateReqVO, "update");
        // 更新
        StoreInitDO updateObj = BeanUtils.toBean(updateReqVO, StoreInitDO.class);
        storeInitMapper.updateById(updateObj);
    }

    @Override
    public void deleteStoreInit(Long id) {
        // 校验存在
        validateStoreInitExists(id);
        // 删除
        storeInitMapper.deleteById(id);
    }

    @Override
    public void deleteStoreInitListByIds(List<Long> ids) {
        // 删除
        storeInitMapper.deleteByIds(ids);
    }


    private void validateStoreInitExists(Long id) {
        if (storeInitMapper.selectById(id) == null) {
            throw exception(STORE_INIT_NOT_EXISTS);
        }
    }

    @Override
    public StoreInitDO getStoreInit(Long id) {
        return storeInitMapper.selectById(id);
    }

    @Override
    public PageResult<StoreInitDO> getStoreInitPage(StoreInitPageReqVO pageReqVO) {
        //判断是否是管理员  超级管理员切换租户无法查询到信息
        if (permissionService.hasAnyRoles(SecurityFrameworkUtils.getLoginUserId(), "super_admin", "tenant_admin")) {//判断是不是管理员
            //查询全部
            if (StringUtils.isNotEmpty(pageReqVO.getCustomerAccount())) {
                pageReqVO.setCustomerAccount(pageReqVO.getCustomerAccount());
            } else {
                pageReqVO.setCustomerAccount(null);
            }
        } else {
            //查询自己的
            Long loginUserId = SecurityFrameworkUtils.getLoginUserId();
            AdminUserDO user = adminUserService.getUser(loginUserId);
            if (user == null) {//管理员切换租户无法查询到
                pageReqVO.setCustomerAccount(null);
            } else {
                String userName = user.getUsername();
                pageReqVO.setCustomerAccount(userName);
            }

        }
        PageResult<StoreInitDO> pageResult = storeInitMapper.selectPage(pageReqVO);
        //计算当前库存
        pageResult.getList().forEach(storeInit -> {
            //期初库存
            Integer initAmount = storeInit.getInitAmount();

            //查询历史出入库
            StoreManagePageReqVO reqVO = new StoreManagePageReqVO();
            reqVO.setCustomerAccount(storeInit.getCustomerAccount());
            reqVO.setDrawingNumber(storeInit.getDrawingNumber());
            Long inCountLong = storeManageMapper.selectInCount(reqVO);
            Integer inCount = (inCountLong == null) ? 0 : inCountLong.intValue();

            Long outCountLong = storeManageMapper.selectOutCount(reqVO);
            Integer outCount = (outCountLong == null) ? 0 : outCountLong.intValue();

            Integer currentAmount = initAmount + inCount - outCount;
            storeInit.setCurrentAmount(currentAmount);

        });


        return pageResult;
    }


    @Override
    public ImportRespVO importList(List<DrawStoreInitImportVo> list, boolean isUpdateSupport) {
        // 1.1 参数校验
        if (CollUtil.isEmpty(list)) {
            throw exception(IMPORT_EQUIPMENT_MANAGE_NOT_EXISTS);
        }

        //2.记录成功或失败记录
        ImportRespVO respVO = ImportRespVO.builder().insertNameList(new ArrayList<>())
                .updateNameList(new ArrayList<>()).failureMap(new LinkedHashMap<>()).build();

        AtomicInteger count = new AtomicInteger(1);
        Long loginUserId = SecurityFrameworkUtils.getLoginUserId();
        AdminUserDO user = adminUserService.getUser(loginUserId);
        String userName = user.getUsername();
        //
        List<StoreInitDO> rusultList = new ArrayList<>();


        list.forEach(drawConfig -> {
            count.incrementAndGet();//记录行号


            if (StringUtils.isEmpty(drawConfig.getDrawingNumber())) {
                throw exception("第" + count + "行数据" + "图号不能为空!");
            }

            if (!userName.equals(drawConfig.getCustomerAccount())) {
                throw exception("第" + count + "行数据" + "客户账号与登录账号不匹配!");
            }

            //
            LambdaQueryWrapper<StoreInitDO> queryWrapper = new LambdaQueryWrapper<StoreInitDO>();
            queryWrapper.eq(StoreInitDO::getCustomerAccount, userName);
            queryWrapper.eq(StoreInitDO::getDrawingNumber, drawConfig.getDrawingNumber());
            boolean exists = storeInitMapper.exists(queryWrapper);
            if (exists) {
                throw exception("第" + count + "行数据" + "图号:" + drawConfig.getDrawingNumber() + " 已存在!");
            }

            //根据
            LambdaQueryWrapper<DrawConfigDO> configWrapper = new LambdaQueryWrapper<DrawConfigDO>();
            configWrapper.eq(DrawConfigDO::getCustomerAccount, userName);
            configWrapper.eq(DrawConfigDO::getDrawingNumber, drawConfig.getDrawingNumber());
            boolean configExists = drawConfigMapper.exists(configWrapper);
            if (!configExists) {
                throw exception("第" + count + "行数据" + "图号:" + drawConfig.getDrawingNumber() + "不存在,请先在图号管理中配置!");
            }
            rusultList.add(BeanUtils.toBean(drawConfig, StoreInitDO.class));
            respVO.getInsertNameList().add(drawConfig.getDrawingNumber());
        });
        if (respVO.getFailureMap().size() > 0) {
            respVO.getInsertNameList().clear();
            return respVO;
        }
        //一次性保存
        storeInitMapper.insertBatch(rusultList);

        return respVO;
    }

    public void checkDrawConfig(StoreInitSaveReqVO reqVO, String type) {
        //根据用户名 图号 判断有无重复的图号 更新操作排除自身
        LambdaQueryWrapper<StoreInitDO> queryWrapper = new LambdaQueryWrapper<StoreInitDO>();
        queryWrapper.eq(StoreInitDO::getCustomerAccount, reqVO.getCustomerAccount());
        queryWrapper.eq(StoreInitDO::getDrawingNumber, reqVO.getDrawingNumber());

        if ("update".equals(type)) {
            queryWrapper.ne(StoreInitDO::getId, reqVO.getId());
        }

        boolean exists = storeInitMapper.exists(queryWrapper);
        if (exists) {
            throw exception("图号:" + reqVO.getDrawingNumber() + " 已存在!");
        }
    }


}